<template></template>
<script lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
export const useLight = () => {
    //是否展示光
    const showLight = ref(false)
    //获取卡片的dom结点
    const cardRef = ref<HTMLDivElement | null>(null)
    // 获取光的dom节点
    let cardOverFlow = ''
    const lightRef = ref<HTMLDivElement | null>(null)

    // 设置卡片的overflow为hidden
    const setCardOverFlowHidden = () => {
        const cardDom = cardRef.value
        if (cardDom) {
            cardOverFlow = cardDom.style.overflow
            cardDom.style.overflow = 'hidden'
        }
    };

    // 重置卡片的overflow
    const reSetCardOverFlow = () => {
        const cardDom = cardRef.value
        if (cardDom) {
            cardDom.style.overflow = cardOverFlow
        }
    };

    //鼠标移入
    const onMouseEnter = () => {
        setCardOverFlowHidden()
        showLight.value = true
    };
    //鼠标移动
    const onMouseMove = (e: MouseEvent) => {
        // 获取鼠标坐标
        const { clientX, clientY } = e
        // 让光跟随鼠标
        const cardDom = cardRef.value
        const lightDom = lightRef.value
        if (cardDom && lightDom) {
            // 获取卡片相对于窗口的x和y坐标
            const { x, y } = cardDom.getBoundingClientRect()
            // 获取光的宽高
            const { width, height } = lightDom.getBoundingClientRect()
            lightDom.style.left = `${clientX - x - width / 2}px`
            lightDom.style.top = `${clientY - y - height / 2}px`
        }
    };
    // 鼠标移出
    const onMouseLeave = () => {
        reSetCardOverFlow()
        showLight.value = false
    };

    onMounted(() => {
        cardRef.value?.addEventListener('mouseenter', onMouseEnter)
        cardRef.value?.addEventListener('mousemove', onMouseMove)
        cardRef.value?.addEventListener('mouseleave', onMouseLeave)
    });

    onUnmounted(() => {
        cardRef.value?.removeEventListener('mouseenter', onMouseEnter)
        cardRef.value?.removeEventListener('mousemove', onMouseMove)
        cardRef.value?.removeEventListener('mouseleave', onMouseLeave)
    });

    return {
        showLight,
        cardRef,
        lightRef
    };
}
</script>
<style scoped></style>